package com.agiantii.ablog.service.impl;

import com.agiantii.ablog.common.Constant;
import com.agiantii.ablog.common.R;
import com.agiantii.ablog.pojo.dto.UserLoginDTO;
import com.agiantii.ablog.pojo.dto.UserRegisterDTO;
import com.agiantii.ablog.pojo.User;
import com.agiantii.ablog.pojo.UserFollow;
import com.agiantii.ablog.mapper.UserMapper;
import com.agiantii.ablog.mapper.UserFollowMapper;
import com.agiantii.ablog.service.UserService;
import com.agiantii.ablog.util.BeanCopyUtils;
import com.agiantii.ablog.pojo.vo.UserVO;
import com.agiantii.ablog.pojo.vo.UserStatsVO;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    
    @Resource
    private UserMapper userMapper;

    @Resource
    private UserFollowMapper userFollowMapper;

    @Override
    public R<User> register(UserRegisterDTO registerDTO) {
        // 检查用户名是否已存在
        if (userMapper.findByUsername(registerDTO.getUsername()) != null) {
            return R.error("用户名已存在", 400);
        }
        
        // 检查邮箱是否已存在
        if (userMapper.findByEmail(registerDTO.getEmail()) != null) {
            return R.error("邮箱已被使用", 400);
        }
        
        // 创建新用户
        User user = new User();
        user.setAvatar(Constant.DEFAULT_COVER);
        BeanUtils.copyProperties(registerDTO, user);
        userMapper.insert(user);
        
        return R.success(user, "注册成功");
    }

    @Override
    public R<User> login(UserLoginDTO loginDTO) {
        User user = userMapper.findByUsername(loginDTO.getUsername());
        
        if (user == null || !user.getPassword().equals(loginDTO.getPassword())) {
            return R.error("用户名或密码错误", 400);
        }
        
        return R.success(user, "登录成功");
    }

    @Override
    public R<User> updateProfile(Long userId, User userUpdate) {
        User user = userMapper.findById(userId);
        if (user == null) {
            return R.error("用户不存在", 404);
        }
        if(userMapper.findByUsername(userUpdate.getUsername())!=null){
            return R.error("用户名已存在", 400);
        }
        user.setUsername(userUpdate.getUsername());
        user.setAvatar(userUpdate.getAvatar());
        user.setBio(userUpdate.getBio());
        userMapper.update(user);
        
        return R.success(user, "更新成功");
    }

    @Override
    public R<Void> follow(Long userId, Long followingId) {
        if (userFollowMapper.findByFollowerAndFollowing(userId, followingId) != null) {
            return R.error("已经关注过该用户", 400);
        }
        
        UserFollow userFollow = new UserFollow();
        userFollow.setFollowerId(userId);
        userFollow.setFollowingId(followingId);
        userFollowMapper.insert(userFollow);
        
        return R.success("关注成功");
    }

    @Override
    public R<Void> unfollow(Long userId, Long followingId) {
        if (userFollowMapper.delete(userId, followingId) == 0) {
            return R.error("未关注该用户", 400);
        }
        
        return R.success("取消关注成功");
    }

    @Override
    public R<User> getUserInfo(Long userId) {
        User user = userMapper.findById(userId);
        if (user == null) {
            return R.error("用户不存在", 404);
        }
        return R.success(user,"获取用户信息成功");
    }

    @Override
    public R<List<UserVO>> getUserList(Integer page, Integer size) {
        PageHelper.startPage(page, size);
        List<User> users = userMapper.findAll();
        PageInfo<User> pageInfo = new PageInfo<>(users);
        
        // 转换为VO
        List<UserVO> userVOs = BeanCopyUtils.copyBeanList(users, UserVO.class);
        
        return R.success(userVOs, "获取用户列表成功").add("total", pageInfo.getTotal());
    }

    @Override
    public R<List<UserVO>> getFollowers(Long userId) {
        List<UserFollow> followers = userFollowMapper.findByFollowingId(userId);
        
        if (followers.isEmpty()) {
            return R.success(new ArrayList<>(), "该用户没有粉丝");
        }
        
        List<Long> followerIds = followers.stream()
                .map(UserFollow::getFollowerId)
                .collect(Collectors.toList());
        
//        PageHelper.startPage(page, size);
        List<User> users = userMapper.findByIds(followerIds);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        
        // 转换为VO
        List<UserVO> userVOs = BeanCopyUtils.copyBeanList(users, UserVO.class);
        
        return R.success(userVOs, "获取粉丝列表成功").add("total", pageInfo.getTotal());
    }

    @Override
    public R<List<UserVO>> getFollowing(Long userId) {
        List<UserFollow> following = userFollowMapper.findByFollowerId(userId);
        
        if (following.isEmpty()) {
            return R.success(new ArrayList<>(), "该用户没有关注的人");
        }
        
        List<Long> followingIds = following.stream()
                .map(UserFollow::getFollowingId)
                .collect(Collectors.toList());
        
//        PageHelper.startPage(page, size);
        List<User> users = userMapper.findByIds(followingIds);
        PageInfo<User> pageInfo = new PageInfo<>(users);
        
        // 转换为VO
        List<UserVO> userVOs = BeanCopyUtils.copyBeanList(users, UserVO.class);
        
        return R.success(userVOs, "获取关注列表成功").add("total", pageInfo.getTotal());
    }

    @Override
    public R<UserStatsVO> getUserStats(Long userId) {
        // 检查用户是否存在
        User user = userMapper.findById(userId);
        if (user == null) {
            return R.error("用户不存在", 404);
        }
        
        // 获取统计数据
        long followersCount = userFollowMapper.countFollowers(userId);
        long followingCount = userFollowMapper.countFollowing(userId);
        long postsCount = userMapper.countUserPosts(userId);
        
        // 构建返回对象
        UserStatsVO stats = UserStatsVO.builder()
                .userId(userId)
                .followersCount(followersCount)
                .followingCount(followingCount)
                .postsCount(postsCount)
                .build();
        
        return R.success(stats, "获取用户统计信息成功");
    }
} 